import React, { createElement, ReactElement } from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { message } from 'antd';
import { getMessage } from '@inbiz/react';
import { routerPrefix } from 'InbizConfig';
import { deepClone, getEditor } from '@inbiz/utils';
import { getProcessInfo } from './service';
import type { SearchCondition } from './types';
import ProcessDetail from './elements/ProcessDetail';
import ProcessDrawerDetail from './elements/ProcessDrawerDetail';
import QuickApproval from './elements/QuickApproval';

function mountModalToBody(node: ReactElement) {
  const wrapper = document.createElement('div', {});
  document.body.appendChild(wrapper);
  render(node, wrapper);
  return {
    unmount() {
      try {
        unmountComponentAtNode(wrapper);
        wrapper?.remove?.();
      } catch (e) {}
    },
  };
}

export function getFormData(
  userInfo: any,
  pageIndex: number,
  pageSize: number,
  rangeConfig: string,
  dptKey: string | undefined,
  name?: string,
  searchCondition?: SearchCondition,
  isDraft?: boolean,
) {
  const params = {
    userId: '',
    starter: '',
    pageIndex: 1,
    pageSize: 50,
    queryParameter: '',
    processGroupName: '',
    processDefinitionId: '',
    date: '',
    status: '',
    processDefId: '',
    dptKey: '',
  };

  params.userId = userInfo?.ID;
  params.starter = userInfo?.ID;
  params.pageIndex = pageIndex;
  params.pageSize = pageSize;
  params.dptKey = rangeConfig == 'all' ? '' : dptKey || '';
  if (name) {
    params.queryParameter = name ?? '';
  }
  if (searchCondition) {
    params.processGroupName = (searchCondition.processGroupName && searchCondition.processGroupName != '-1') ? searchCondition.processGroupName : '';
    params.processDefinitionId = (searchCondition.processDefId && searchCondition.processDefId != '-1') ? searchCondition.processDefId : '';
    params.date = (searchCondition.date && searchCondition.date != '-1') ? searchCondition.date : '';
    params.status = (searchCondition.status && searchCondition.status != '-1') ? searchCondition.status : '';
  }
  if (searchCondition && isDraft) {
    params.processDefId = (searchCondition.processDefId && searchCondition.processDefId != '-1') ? searchCondition.processDefId : '';
  }
  return params;
}

export const toggleSelect = (bool: boolean, list: { task_id: string }[], callback: Function) => {
  if (getEditor()) {
    return;
  }
  const arr = list.map((item: { task_id: string }) => ({
    ...item,
    checked: bool,
  }));
  callback(arr);
};

export const statusList = [
  { id: '-1', name: 'processCenter.status' },
  {
    id: '',
    name: 'processCenter.all',
    iconType: 'icon-a-suoyou',
  },
  {
    id: '10',
    name: 'processCenter.beenreturnsBack',
    iconType: 'icon-beituihui',
  },
  {
    id: '0',
    name: 'processCenter.approvaling',
    iconType: 'icon-a-shenpizhong',
  },
];
export const myapplystatusList = [
  { id: '-1', name: 'processCenter.status' },
  {
    id: '',
    name: 'processCenter.all',
    iconType: 'icon-a-suoyou',
  },
  {
    id: '1',
    name: 'processCenter.complete',
    iconType: 'icon-zhuangtai-wancheng',
  },
  {
    id: '0',
    name: 'processCenter.approvaling',
    iconType: 'icon-a-shenpizhong',
  },
];
export const dateList = [
  { id: '-1', name: 'processCenter.date' },
  {
    id: '',
    name: 'processCenter.all',
    iconType: 'icon-a-riqisuoyou',
  },
  {
    id: 'days',
    name: 'processCenter.days',
    iconType: 'icon-a-yitiannei',
  },
  {
    id: 'week',
    name: 'processCenter.week',
    iconType: 'icon-a-yizhounei',
  },
  {
    id: 'month',
    name: 'processCenter.month',
    iconType: 'icon-a-yiyuenei',
  },
];

export const afterOperation = (res: any, callback?: Function) => {
  if (res.code == '200' || res.isSuccess) {
    message.success(res.message);
    callback && callback();
  } else {
    message.error(res.message);
  }
};

export const getLogInfo = (e: React.MouseEvent, params: any, callback: Function, $logInfo: Function, setLoading?: Function) => {
  if (getEditor()) {
    return;
  }
  e.stopPropagation();
  setLoading && setLoading(true);
  getProcessInfo(params).then((res) => {
    if (res?.code != 200) {
      message.error(res?.message);
      setLoading && setLoading(false);
      return;
    }
    if (res.details && res.details.length > 0) {
      $logInfo({
        processId: res.details[0].processDefinitionId ?? res.details[0].processId,
        instanceId: params?.processInstanceId,
      });
      setLoading && setLoading(false);
      callback(true);
    }
  });
};

export const clickRow = (record, rowSelection, multiple, choosedItem?) => {
  if (getEditor()) {
    return;
  }
  const { selectedRowKeys, onChange } = rowSelection;
  if (multiple) {
    const index = selectedRowKeys.findIndex(
      (item) => item == record.taskId || item == record.Id || item == record.id,
    );
    if (index == -1) {
      if (choosedItem) {
        onChange([...selectedRowKeys, record.taskId], [...choosedItem, record]);
      } else {
        onChange([...selectedRowKeys, record.taskId ?? record.Id ?? record.id]);
      }
    } else {
      const newKeys = deepClone(selectedRowKeys);
      newKeys.splice(index, 1);

      if (choosedItem) {
        const newItems = deepClone(choosedItem);
        newItems.splice(index, 1);
        onChange(newKeys, newItems);
      } else {
        onChange(newKeys);
      }
    }
  } else {
    onChange([record.taskId ?? record.draftsId ?? record.processInstanceId ?? record.id], []);
  }
};

// 流程中心页面跳转
export const handleClick = (item, pagestring) => {
  if (getEditor()) {
    return;
  }
  if (pagestring) {
    const { origin, pathname, search } = window.location;
    const url = `${origin}${pathname}${search}#${routerPrefix}${pagestring}?tabKey=${item.id}`;
    window.open(url);
  } else {
    message.warn(getMessage('processCenter.setPage'));
  }
};

export const goProcessDetail = (
  title: string,
  url: string,
  version: string,
  request: Function,
  openPopUpHeight?: any,
  openPopUpWidth?: any,
) => {
  let _width =
    openPopUpWidth?.type == '%'
      ? document.body.clientWidth * (openPopUpWidth?.value / 100)
      : openPopUpWidth?.value;
  let _height =
    openPopUpHeight?.type == '%'
      ? document.body.clientHeight * (openPopUpHeight?.value / 100)
      : openPopUpHeight?.value;
  const { unmount } = mountModalToBody(
    createElement(ProcessDetail, {
      bodyHeight: _height || '',
      url,
      version,
      doneHandler: () => {
        request();
      },
      unmount: () => {
        unmount();
      },
      modalParams: {
        visible: true,
        width: _width ? _width + 'px' : 1000,
        footer: null,
        title: title,
        onCancel: async () => {
          unmount();
        },
        wrapClassName: 'processCenter-easy-item-process-detail-modal',
        style: openPopUpHeight
          ? {
              height: _height + 'px',
            }
          : {},
      },
    }),
  );
};

export const goProcessDrawerDetail = (
  title: string,
  url: string,
  version: string,
  request: Function,
  drawerWidth?: any,
) => {
  let _width =
    drawerWidth?.type == '%'
      ? document.body.clientWidth * (drawerWidth?.value / 100)
      : drawerWidth?.value;
  const { unmount } = mountModalToBody(
    createElement(ProcessDrawerDetail, {
      url,
      version,
      doneHandler: () => {
        request();
      },
      unmount: () => {
        unmount();
      },
      drawerParams: {
        visible: true,
        placement: 'right',
        // destroyOnClose: true,
        width: _width ? _width + 'px' : 1000,
        footer: null,
        title: title,
        onClose: async () => {
          unmount();
        },
        className: 'processCenter-easy-item-process-detail-drawer',
      },
    }),
  );
};

// 快速审批
export const goQuickApproval = (data: any[], goView: any, goGetLogInfo: any, ID: string, afterQuickApproval: any) => {
  const { unmount } = mountModalToBody(
    createElement(QuickApproval, {
      unmount: () => {
        unmount();
      },
      data,
      ID,
      goView,
      goGetLogInfo,
      afterQuickApproval,
      modalParams: {
        visible: true,
        footer: null,
        title: getMessage('processCenter.quickApproval'),
        onCancel: async () => {
          unmount();
        },
        wrapClassName: 'processCenter-quick-approval-modal',
      },
    }),
  );
}